package com.ccteam.admin.view.fragments.artist

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.setFragmentResultListener
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ccteam.admin.R
import com.ccteam.admin.REFRESH_REQUEST_KEY
import com.ccteam.admin.core.ADD_TYPE
import com.ccteam.admin.core.EDIT_TYPE
import com.ccteam.admin.databinding.ArtistHomeInfoItemBinding
import com.ccteam.admin.databinding.FragmentArtistHomeBinding
import com.ccteam.admin.utils.EventObserver
import com.ccteam.admin.viewmodels.artist.ArtistHomeViewModel
import com.ccteam.model.artist.ArtistVO
import com.orhanobut.logger.Logger
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

@AndroidEntryPoint
class ArtistHomeFragment : Fragment() {

    private var _binding: FragmentArtistHomeBinding? = null
    private val binding get() = _binding!!

    private val artistHomeViewModel: ArtistHomeViewModel by viewModels()

    private lateinit var adapter: ArtistListRVAdapter

    private val callback = object: ArtistItemClicked{
        override fun itemClick(item: ArtistVO) {
            findNavController().navigate(
                ArtistHomeFragmentDirections
                    .actionArtistHomeFragmentToArtistEditFragment(EDIT_TYPE,item.id))
        }

    }

    companion object{
        val differCallback = object: DiffUtil.ItemCallback<ArtistVO>(){

            override fun areItemsTheSame(oldItem: ArtistVO, newItem: ArtistVO): Boolean {
                return oldItem == newItem
            }

            override fun areContentsTheSame(oldItem: ArtistVO, newItem: ArtistVO): Boolean {
                return oldItem == newItem
            }

        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentArtistHomeBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        adapter = ArtistListRVAdapter(callback)
        binding.rvAlbumList.adapter = adapter

        binding.btnAdd.setOnClickListener{
            findNavController().navigate(
                ArtistHomeFragmentDirections
                    .actionArtistHomeFragmentToArtistEditFragment(ADD_TYPE,null))
        }

        // 分页内容
        viewLifecycleOwner.lifecycleScope.launch {
            artistHomeViewModel.artistListFlow.collectLatest { artistList ->
                adapter.submitData(artistList)
            }
        }

        binding.refreshView.setOnRefreshListener {
             adapter.refresh()
        }

        viewLifecycleOwner.lifecycleScope.launch {
            adapter.loadStateFlow.collectLatest { state ->
                binding.statusView.changeToLoadingStatus(state.refresh is LoadState.Loading)
                binding.statusView.changeToErrorStatus(state.refresh,
                    state.append.endOfPaginationReached && adapter.itemCount < 1)
                binding.refreshView.isRefreshing = state.refresh is LoadState.Loading
            }
        }

        binding.statusView.setRetryClickListener {
            adapter.retry()
        }
    }

    override fun onResume() {
        super.onResume()

        setFragmentResultListener(REFRESH_REQUEST_KEY) { _, bundle ->
            if(bundle.getBoolean(REFRESH_REQUEST_KEY)){
                viewLifecycleOwner.lifecycleScope.launch {
                    delay(100L)
                    adapter.refresh()
                }
            }
        }
    }


    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    /**
     * 基于分页 [PagingDataAdapter] 的RecyclerView 适配器
     */
    class ArtistListRVAdapter(
        val callback: ArtistItemClicked
    ): PagingDataAdapter<ArtistVO, ArtistListRVAdapter.ArtistInfoViewHolder>(
        differCallback){

        inner class ArtistInfoViewHolder(
            val binding: ArtistHomeInfoItemBinding
        ): RecyclerView.ViewHolder(binding.root){
            var item: ArtistVO? = null
            init {

                binding.root.setOnClickListener {
                    item?.let {
                        callback.itemClick(it)
                    }
                }
            }
        }

        override fun onBindViewHolder(holder: ArtistInfoViewHolder, position: Int) {
            val item = getItem(position)
            holder.item = item
            holder.binding.tvArtistName.text = item?.name ?: "未知"
            holder.binding.tvArtistTrackNum.text = item?.trackNum.toString()
            holder.binding.tvArtistAlbumNum.text = item?.albumNum.toString()

            Glide.with(holder.binding.ivArtistPhoto)
                .load(item?.imgUrl)
                .placeholder(R.drawable.img_default_artist)
                .into(holder.binding.ivArtistPhoto)
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArtistInfoViewHolder {
             return ArtistInfoViewHolder(ArtistHomeInfoItemBinding.inflate(LayoutInflater.from(parent.context),parent,false))
        }
    }

    interface ArtistItemClicked{
        fun itemClick(item: ArtistVO)
    }
}